package server;

import java.io.BufferedReader;
import java.io.IOException;

import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Jacek
 */
public class Client implements Runnable {

    public Thread thread;
    private String name;
    private Socket Socket;
    private PrintWriter Out = null;
    private BufferedReader In = null;
    private boolean Active;
    private String buffor;
    ClientList clientList;

    public Client(String name) {
        this.name = name;
        Active = false;
    }

    public void setList(ClientList list){
        clientList=list;
    }
    public void setActive(Socket socket) throws IOException {
        this.Socket = socket;
        Out = new PrintWriter(socket.getOutputStream(), true);
        In = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        name=read();
        thread=new Thread(this);
        thread.start();
        Active = true;
    }

    public void send(String text) {
        Out.println(text);
        Out.flush();
    }

    public String read() throws IOException {
        return In.readLine();
    }

    /**
     * @return the active
     */
    public boolean isActive() {
        return Active;
    }
    public String GetName(){
        return name;
    }

    @Override
    public void run() {  
        String[] pom;
        try {
            while (Active) {  
                    buffor = In.readLine();
                    if (buffor.equals("quit")) {
                        clientList.RemoveFromList(this);
                        In.close();
                        Active = false;
                        System.out.println("Client was quit from application.");        
                    }
                    if (buffor.equals("list")) {
                        send(clientList.getList());   
                    }
                    if(buffor.contains("~")){
                        pom=buffor.split("~");
                        clientList.SendTo(pom[1], pom[0]);
                    }
            }
        } catch (IOException ex) {
             System.out.println(ex.getMessage());
        }
        catch (Exception ex) {
             System.out.println(ex.getMessage());
        }
    }
}
